<template>
  <div class="cart-container">
    <el-page-header @back="goBack" title="返回">
      <template #content>
        <h1>我的购物车</h1>
      </template>
    </el-page-header>

    <div v-loading="loading" class="cart-content">
      <!-- 学生未绑定提示 -->
      <el-empty 
        v-if="showBindPrompt" 
        description="您还未绑定学生信息"
      >
        <el-button type="primary" @click="goToBindPage">去绑定</el-button>
      </el-empty>

      <!-- 购物车为空提示 -->
      <el-empty 
        v-else-if="!loading && cartCourses.length === 0" 
        description="购物车空空如也~"
      >
        <el-button type="primary" @click="goToCourseList">去选课</el-button>
      </el-empty>

      <!-- 购物车课程列表 -->
      <el-card v-else shadow="hover" class="cart-list">
        <div class="cart-actions">
          <el-checkbox 
            v-model="selectAll" 
            @change="handleSelectAllChange"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
          <el-button 
            type="danger" 
            plain
            :disabled="selectedCourses.length === 0" 
            @click="batchRemove"
            class="batch-delete-btn"
          >
            <el-icon><Delete /></el-icon> 删除选中 ({{ selectedCourses.length }})
          </el-button>
        </div>

        <div v-for="course in cartCourses" :key="course.id" class="cart-item">
          <el-checkbox 
            v-model="selectedCourses" 
            :label="course.id" 
            class="course-checkbox" 
          />
          <el-row :gutter="20" align="middle">
            <el-col :span="4">
              <el-image 
                :src="getCourseCover(course)" 
                class="course-cover" 
                fit="cover"
                @click="goToCourseDetail(course.id)"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </el-col>
            <el-col :span="14">
              <h3 @click="goToCourseDetail(course.id)">{{ course.name }}</h3>
              <p class="course-intro">{{ course.introduction || '暂无课程介绍' }}</p>
              <div class="course-stats">
                <el-tag size="small" type="info">
                  <el-icon><SoldOut /></el-icon> {{ course.purchaseCount || 0 }}人购买
                </el-tag>
                <el-tag size="small" type="warning" style="margin-left: 8px;">
                  <el-icon><Star /></el-icon> {{ course.likeCount || 0 }}人收藏
                </el-tag>
              </div>
            </el-col>
            <el-col :span="4" class="price-col">
              <span class="price">¥{{ formatPrice(course.price) }}</span>
              <p v-if="course.originalPrice && course.originalPrice > course.price" class="discount-price">
                <del>¥{{ formatPrice(course.originalPrice) }}</del>
                <span class="discount-tag">{{ calculateDiscount(course) }}折</span>
              </p>
            </el-col>
            <el-col :span="2">
              <el-button 
                type="danger" 
                :icon="Delete" 
                circle
                plain
                @click.stop="removeFromCart(course.id)"
                class="single-delete-btn"
              />
            </el-col>
          </el-row>
        </div>

        <div class="cart-footer">
          <div class="selection-info">
            已选 {{ selectedCourses.length }} 门课程
          </div>
          <div class="total-section">
            <div class="total-price">
              合计：<span class="price">¥{{ formatPrice(selectedTotalPrice) }}</span>
            </div>
            <div v-if="totalDiscount > 0" class="total-discount">
              已省：<span class="price">¥{{ formatPrice(totalDiscount) }}</span>
            </div>
          </div>
          <el-button 
            type="primary" 
            size="large"
            :disabled="selectedCourses.length === 0"
            @click="batchCheckout"
            class="checkout-btn"
          >
            立即结算 ({{ selectedCourses.length }}门)
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  ElMessage, 
  ElMessageBox,
  ElImage,
  ElIcon 
} from 'element-plus'
import { 
  Delete, 
  Picture,
  SoldOut,
  Star
} from '@element-plus/icons-vue'
import { studentApi } from '@/api/students'
import { useAuthStore } from '@/stores/auth'
import axios from 'axios'

const router = useRouter()
const authStore = useAuthStore()
const loading = ref(false)
const cartCourses = ref([])
const selectedCourses = ref([])
const selectAll = ref(false)
const showBindPrompt = ref(false)
const defaultCourseImage = ref(require('@/assets/fault.png'))

// 计算半选状态
const isIndeterminate = computed(() => {
  return selectedCourses.value.length > 0 && 
         selectedCourses.value.length < cartCourses.value.length
})

// 价格格式化（分转元）
const formatPrice = (price) => {
  if (!price) return '0.00'
  return (price / 100).toFixed(2)
}

// 计算折扣率
const calculateDiscount = (course) => {
  if (!course.originalPrice || !course.price) return 0
  return Math.round((course.price / course.originalPrice) * 10)
}

// 获取课程封面图
const getCourseCover = (course) => {
  return course.coverUrl || course.couPic || defaultCourseImage.value
}

// 计算选中课程总价
const selectedTotalPrice = computed(() => {
  return selectedCourses.value.reduce((sum, courseId) => {
    const course = cartCourses.value.find(c => c.id === courseId)
    return sum + (course?.price || 0)
  }, 0)
})

// 计算总优惠金额
const totalDiscount = computed(() => {
  return selectedCourses.value.reduce((sum, courseId) => {
    const course = cartCourses.value.find(c => c.id === courseId)
    return sum + ((course?.originalPrice || 0) - (course?.price || 0))
  }, 0)
})

// 获取购物车课程
const fetchCartCourses = async () => {
  try {
    loading.value = true
    showBindPrompt.value = false
    
    if (!authStore.isAuthenticated) {
      throw new Error('用户未登录')
    }

    // 获取学生ID
    const studentResponse = await studentApi.getStudentIdByUserId(authStore.userId)
    
    if (!studentResponse.success || !studentResponse.data) {
      showBindPrompt.value = true
      throw new Error(studentResponse.message || '获取学生信息失败，请先绑定学生信息')
    }

    const studentId = studentResponse.data

    // 直接调用接口获取购物车数据
    const response = await axios.get(`/api/cart/student-courses?studentId=${studentId}`)
    
    if (response.status === 200) {
      cartCourses.value = response.data || []
      selectedCourses.value = []
      selectAll.value = false
    } else {
      throw new Error('获取购物车数据失败')
    }
  } catch (error) {
    console.error('获取购物车失败:', error)
    ElMessage.error(`获取购物车失败: ${error.message}`)
    cartCourses.value = []
  } finally {
    loading.value = false
  }
}

// 全选/取消全选
const handleSelectAllChange = (val) => {
  selectedCourses.value = val ? cartCourses.value.map(course => course.id) : []
}

// 批量删除
const batchRemove = async () => {
  try {
    if (selectedCourses.value.length === 0) {
      ElMessage.warning('请先选择要删除的课程')
      return
    }

    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedCourses.value.length} 门课程吗？`,
      '确认删除',
      { 
        type: 'warning',
        confirmButtonText: '确认删除',
        cancelButtonText: '取消'
      }
    )

    const studentResponse = await studentApi.getStudentIdByUserId(authStore.userId)
    const studentId = studentResponse.data
    
    if (!studentId) {
      throw new Error('获取学生信息失败')
    }

    // 直接调用接口批量删除
    const response = await axios.delete('/api/cart/batch-remove-courses', {
      data: {
        studentId,
        courseIds: selectedCourses.value
      }
    })

    if (response.status === 200) {
      ElMessage.success(`已删除 ${selectedCourses.value.length} 门课程`)
      selectedCourses.value = []
      await fetchCartCourses()
    } else {
      throw new Error(response.data?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error(`删除失败: ${error.message}`)
    }
  }
}

// 单个课程删除
const removeFromCart = async (courseId) => {
  try {
    await ElMessageBox.confirm('确定要移除该课程吗？', '提示', { 
      type: 'warning',
      confirmButtonText: '确定移除',
      cancelButtonText: '取消'
    })

    const studentResponse = await studentApi.getStudentIdByUserId(authStore.userId)
    const studentId = studentResponse.data
    
    if (!studentId) {
      throw new Error('获取学生信息失败')
    }

    // 直接调用接口删除单个课程
    const response = await axios.delete(`/api/cart/remove-course/${courseId}?studentId=${studentId}`)
    
    if (response.status === 200) {
      ElMessage.success('已移除课程')
      selectedCourses.value = selectedCourses.value.filter(id => id !== courseId)
      await fetchCartCourses()
    } else {
      throw new Error(response.data?.message || '移除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程失败:', error)
      ElMessage.error(`移除失败: ${error.message}`)
    }
  }
}

// 批量结算
// 批量结算
const batchCheckout = async () => {
  try {
    if (selectedCourses.value.length === 0) {
      ElMessage.warning('请先选择要结算的课程')
      return
    }

    const confirmResult = await ElMessageBox.confirm(
      `确认结算 ${selectedCourses.value.length} 门课程？总金额: ¥${formatPrice(selectedTotalPrice.value)}`,
      '订单确认',
      {
        confirmButtonText: '确认支付',
        cancelButtonText: '再想想',
        distinguishCancelAndClose: true,
        type: 'warning'
      }
    )

    if (confirmResult === 'confirm') {
      const studentResponse = await studentApi.getStudentIdByUserId(authStore.userId)
      const studentId = studentResponse.data
      
      if (!studentId) {
        throw new Error('获取学生信息失败')
      }

      // 1. 先创建订单
      const orderResponse = await axios.post('/api/cart/batch-create-orders', {
        studentId,
        courseIds: selectedCourses.value,
        totalAmount: selectedTotalPrice.value
      })

      if (orderResponse.status === 200) {
        const order = orderResponse.data
        if (order && order.id) {
          // 2. 订单创建成功后，将课程添加到学生课程表
          try {
            // 批量添加课程到学生课程表
            const addCoursePromises = selectedCourses.value.map(courseId => 
              axios.post(`/api/student/classes/${studentId}/courses/${courseId}`)
            )
            
            await Promise.all(addCoursePromises)
            
            // 3. 从购物车移除课程
            await axios.delete('/api/cart/batch-remove-courses', {
              data: {
                studentId,
                courseIds: selectedCourses.value
              }
            })
            
            // 4. 跳转到订单详情页
            router.push(`/order/detail/${order.id}`)
            ElMessage.success('订单创建成功，课程已添加到您的学习列表')
            await fetchCartCourses()
          } catch (addCourseError) {
            console.error('添加课程到学生课程表失败:', addCourseError)
            ElMessage.error(`课程添加失败: ${addCourseError.message}`)
          }
        } else {
          throw new Error('订单创建失败')
        }
      } else {
        throw new Error(orderResponse.data?.message || '订单创建失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('结算失败:', error)
      ElMessage.error(`结算失败: ${error.message}`)
    }
  }
}



// 跳转到课程详情
const goToCourseDetail = (courseId) => {
  router.push(`/course/detail/${courseId}`)
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 去课程列表
const goToCourseList = () => {
  router.push('/student/course-selection')
}

// 去绑定页面
const goToBindPage = () => {
  router.push('/student/bind')
}

onMounted(() => {
  if (authStore.isAuthenticated) {
    fetchCartCourses()
  } else {
    router.push('/login?redirect=/student/shopcart')
  }
})
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.cart-content {
  margin-top: 20px;
}

.cart-list {
  margin-top: 20px;
  padding: 15px;
}

.cart-actions {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px 0;
  margin-bottom: 15px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  transition: all 0.3s ease;
}

.cart-item:hover {
  background-color: var(--el-fill-color-light);
}

.cart-item:last-child {
  border-bottom: none;
}

.course-checkbox {
  margin-right: 15px;
  flex-shrink: 0;
}

.course-cover {
  width: 100%;
  height: 100px;
  border-radius: 4px;
  cursor: pointer;
  object-fit: cover;
  transition: transform 0.3s;
}

.course-cover:hover {
  transform: scale(1.03);
}

.image-error {
  width: 100%;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-fill-color-light);
  color: var(--el-text-color-placeholder);
}

.course-intro {
  color: var(--el-text-color-secondary);
  margin: 5px 0;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

h3 {
  cursor: pointer;
  transition: color 0.2s;
  margin: 0;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

h3:hover {
  color: var(--el-color-primary);
}

.course-stats {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.price-col {
  text-align: right;
}

.price {
  font-size: 18px;
  color: var(--el-color-danger);
  font-weight: bold;
}

.discount-price {
  margin-top: 5px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.discount-price del {
  margin-right: 5px;
}

.discount-tag {
  color: var(--el-color-danger);
  font-weight: bold;
}

.cart-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 30px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-light);
}

.total-section {
  text-align: right;
}

.total-price {
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.total-price .price {
  font-size: 24px;
}

.total-discount {
  font-size: 14px;
  color: var(--el-color-success);
  margin-top: 5px;
}

.selection-info {
  color: var(--el-text-color-secondary);
  margin-right: auto;
}

/* 按钮样式优化 */
.batch-delete-btn {
  margin-left: 15px;
  transition: all 0.3s;
}

.batch-delete-btn:hover {
  transform: translateY(-1px);
}

.single-delete-btn {
  transition: all 0.3s;
}

.single-delete-btn:hover {
  transform: scale(1.1);
}

.checkout-btn {
  transition: all 0.3s;
  min-width: 180px;
}

.checkout-btn:hover {
  transform: translateY(-2px);
}

.checkout-btn:active {
  transform: translateY(0);
}

.checkout-btn:disabled {
  opacity: 0.6;
  transform: none;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .cart-actions {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .batch-delete-btn {
    margin-left: 0;
    width: 100%;
  }
  
  .cart-footer {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .total-section {
    text-align: left;
    width: 100%;
  }
  
  .checkout-btn {
    width: 100%;
  }
}
</style>